package org.gameis.furtal.server.network;

import org.gameis.furtal.FurtalProtocol;
import org.gameis.furtal.utils.FurtalUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.text.SimpleDateFormat;

/**
 * Created by IntelliJ IDEA.
 * User: zvoykish
 * Date: 27/1/12
 * Time: 12:37 PM
 */
public class ConnectionHandler implements Runnable {

    private Socket socket;
    private final FurtalProtocol protocol;

    public ConnectionHandler(Socket socket) {
        this.socket = socket;
        this.protocol = new FurtalProtocol();
    }

    public Socket getSocket() {
        return socket;
    }

    public void run() {
        InetAddress address = socket.getInetAddress();
        FurtalUtils.print("ConnectionHandler started for: " + address);
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream());
            String inputLine, outputLine;

            outputLine = protocol.processInput(null);
//            out.print(outputLine);

            while ((inputLine = in.readLine()) != null) {
                if (inputLine.endsWith("\u0000"))
                FurtalUtils.print("Received message from client: " + inputLine);
                outputLine = protocol.processInput(inputLine);
                FurtalUtils.print("Sending response to client: " + outputLine);
                out.print(outputLine);
//                if (outputLine.equals(FurtalConstants.BYE_RESPONSE)) {
//                    break;
//                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                out.close();
            }
        }
        FurtalUtils.print("ConnectionHandler ended for: " + address);
    }
}
